<template>
  <!-- 播放器 -->
  <div class="song">
    <audio ref="player" :src="this.musicSrc" autoplay controls loop></audio>
    <div class="pic" v-if="this.picUrl==''"  @click="toPlay"></div>
    <img class="pic" v-else :src="picUrl"  @click="toPlay" />
  </div>
</template>

<script>
import bus from "@/bus.js";
export default {
  data() {
    return {
      musicSrc: "",
      picUrl: "",
      durationTime: 0,
      currentTime: 0
    };
  },
  mounted() {
    // 接收歌曲信息，拿到音频和图片
    bus.$on("musicUrl", res => {
      if (res) {
        this.musicSrc = res.url;
        this.picUrl = res.al.picUrl;
      }
    });
    // 调用监听函数
    this.addEventListeners();
  },
  methods: {
    // 监听当前时间
    addEventListeners() {
      this.$refs.player.addEventListener("timeupdate", this._currentTime),
        this.$refs.player.addEventListener("canplay", this._durationTime);
    },
    // 移除监听
    removeEventListeners: function() {
      this.$refs.player.removeEventListener("timeupdate", this._currentTime);
      this.$refs.player.removeEventListener("canplay", this._durationTime);
    },
    _currentTime() {
      this.currentTime = this.$refs.player.currentTime;
      // 修改仓库中的当前时间
      this.$store.commit('changeTime',this.currentTime);
    },
    _durationTime() {
      this.durationTime = this.$refs.player.duration;
      // 修改仓库中的总时间
      this.$store.commit('changeDurationTime',this.durationTime);
    },
    toPlay() {
      // 跳转页面
      this.$router.push("/musicPlay");
    }
  },
  // 移除
  beforeDestroy() {
    this.removeEventListeners();
  }
};
</script>
<style scoped>
.pic {
  width: 40px;
  height: 40px;
  position: fixed;
  bottom: 0;
  z-index: 999;
  right: 20px;
  border-radius: 100%;
}
div[class="pic"] {
  background-color: #fff;
  border-radius: 100%;
}
audio {
  height: 40px;
  width: 80%;
  border-radius: 0;
}
</style>